package com.leigang.simple.controller;

import com.leigang.simple.service.IGenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

@Slf4j
@RestController
public class GenController {
    private final IGenService genService;

    public GenController(IGenService genService) {
        this.genService = genService;
    }

    @Value("${file.path}")
    public String filePath;
    @Value("${image.after.thread.sleep}")
    public Integer imageAfterThreadSleep;

    @PostMapping
    public void gen(@RequestBody Map<String, String> map, HttpServletResponse response) throws Exception {
        String url = map.get("url");
        log.info("=========开始截图=============请求地址：{}", url);
        genService.genImage(url);
        log.info("=========截图完成=============");
        Thread.sleep(imageAfterThreadSleep);
        log.info("=========图片生成开始==========");
        try (InputStream inputStream = Files.newInputStream(Paths.get(filePath));
             OutputStream os = response.getOutputStream()) {
            if (inputStream != null) {
                int read;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    // 处理读取到的字节，例如打印到控制台
                    os.write(bytes, 0, read);
                }
                os.flush();
            } else {
                log.error("文件未找到: " + filePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("========图片生成完成========");
    }
}
